package NES::Cartridge;

use strict;
use Data::Dumper;

sub new {
    my $class = shift;

    my $self = bless {
        file      => '',
        mirroring => undef,
        @_,
    }, $class;

    $self->load_data();

    return $self;
}

sub get_file {
    my $self = shift;

    return $self->{file};
}

sub get_mirroring {
    my $self = shift;

    return $self->{mirroring};
}

sub load_data {
    my $self = shift;


    my $temp = $/;

    print "Loading < $self->{file} >$/";

    open my $f, '<', $self->{file} or die $!;
    local undef $/;
    my @data = map { hex($_) } grep { $_ } ( split /(..)/, (unpack 'H*', <$f>) );
    close $f;

    $/ = $temp;

    # prg-rom banks
    my $rom_banks = int( $data[4] );
    print "PRG-ROM banks: $rom_banks$/";

    # mirroring
    $self->{mirroring} = int( $data[6] );
    printf "Mirroring type: %s$/Loading PRG-ROM banks$/", ( $self->{mirroring} == 1 ? 'vertical' : 'horizontal' );

    my $offset = 16;

    # ram
    if( $rom_banks == 1 ) {
        $offset += 0x4000;
        for( my $i = 0; $i < 0x4000; $i++ ) {
            $self->{memory}{ram}[ 0x8000 + $i ] = $data[ 16 + $i ]; # nestest.nes only!
            $self->{memory}{ram}[ 0xc000 + $i ] = $data[ 16 + $i ];
        }
    } elsif( $rom_banks == 2 ) {
        $offset += 0x8000;
        for( my $i = 0; $i < 0x8000; $i++ ) {
            $offset++;
            $self->{memory}{ram}[ 0x8000 + $i ] = $data[ 16 + $i ];
        }
    } else {
        die "Too many PRG-ROM banks :($/";
    }

    # vram
    for( my $i = 0; $i < 0x2000; $i++ ) {
        $self->{memory}{vram}[ $i ] = $data[ $offset + $i ];
    }

    delete $self->{memory};

    print "Load OK!$/";
}

1;